<template>
  <view class="container">
    <!-- 商品图片轮播 -->
    <swiper 
      class="product-swiper" 
      circular 
      indicator-dots
      :current="currentSwiperIndex"
      @change="handleSwiperChange"
    >
      <swiper-item v-for="(image, index) in allImages" :key="index">
        <image 
          :src="image || '/static/logo.png'"
          mode="aspectFill" 
          class="product-image"
          @tap="previewImage(image)"
        />
      </swiper-item>
    </swiper>

    <!-- 商品信息 -->
    <view class="product-info">
      <view class="price-section">
        <text class="price">¥{{ selectedSku?.price || product?.minPrice || '0.00' }}</text>
        <!-- <text class="original-price" v-if="selectedSku?.originalPrice">¥{{ selectedSku.originalPrice }}</text> -->
        <text class="stock-info" v-if="selectedSku">库存: {{ selectedSku.stock }}</text>
        <text class="sales-info">已售{{ product?.sales || 0 }}</text>
      </view>
      <view class="name-section">
        <text :class="['name', { 'expanded': isNameExpanded }]">{{ product?.name }}</text>
        <text v-if="product?.name && product.name.length > 50" class="expand-btn" @tap="isNameExpanded = !isNameExpanded">
          {{ isNameExpanded ? '收起' : '展开' }}
        </text>
      </view>
      <view class="desc-section">
        <text :class="['desc', { 'expanded': isDescExpanded }]">{{ selectedSku?.description || product?.description }}</text>
        <text v-if="(selectedSku?.description || product?.description || '').length > 50" 
          class="expand-btn" 
          @tap="isDescExpanded = !isDescExpanded"
        >
          {{ isDescExpanded ? '收起' : '展开' }}
        </text>
      </view>
      <view class="selected-info" v-if="selectedSku">
        <text class="label">已选</text>
        <view class="value">
          <text class="selected-desc">{{ selectedSku.quantity }}</text>
          <view class="quantity-control">
            <button 
              class="quantity-btn"
              :class="{ disabled: buyQuantity <= 1 }"
              @tap="updateBuyQuantity(-1)"
            >-</button>
            <text class="quantity">{{ buyQuantity }}</text>
            <button 
              class="quantity-btn"
              :class="{ disabled: buyQuantity >= (selectedSku?.stock || 0) }"
              @tap="updateBuyQuantity(1)"
            >+</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 规格选择 -->
    <view class="specs-section" v-if="product?.productSKUVOList?.length">
      <view class="section-title">规格选择</view>
      <scroll-view
          scroll-x
          class="specs-scroll"
          show-scrollbar="false"
          enhanced
          :scroll-into-view="'sku-' + selectedSku?.id"
      >
        <view class="specs-row">
          <view
              v-for="(sku, index) in product.productSKUVOList"
              :key="sku.id"
              :id="'sku-' + sku.id"
              class="spec-item"
              :class="{
              active: selectedSku?.id === sku.id,
              disabled: !sku?.stock || sku.stock <= 0
            }"
              @tap="sku?.stock && sku.stock > 0 && selectSku(sku, index + 1)"
          >
            <image
                :src="sku.image || product.image || '/static/logo.png'"
                mode="aspectFill"
                class="spec-image"
                @tap.stop="selectSku(sku, index + 1)"
            />
            <view class="spec-info">
              <text class="spec-name">{{ sku.description || '默认规格' }}</text>
              <view class="spec-price-info">
                <text class="spec-price">¥{{ sku.price }}</text>
                <text class="spec-original-price" v-if="sku.originalPrice">¥{{ sku.originalPrice }}</text>
              </view>
              <text class="spec-stock" :class="{ 'low-stock': sku.stock < 10 }">
                {{ sku.stock > 0 ? `库存: ${sku.stock}` : '已售罄' }}
              </text>
            </view>
            <view class="selected-mark" v-if="selectedSku?.id === sku.id">
              <text class="mark-icon">✓</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="section-title">商品详情</view>
      <rich-text :nodes="product?.description || '' "></rich-text>
    </view>

    <!-- 商品评价 -->
    <product-reviews 
      :reviews="reviews" 
      :total="total" 
      :has-more="hasMore"
      @load-more="loadMoreReviews"
    />

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="left-actions">
        <view class="action-item" @tap="goToCart">
          <image src="/static/cart.png" class="action-icon"/>
          <text>购物车</text>
        </view>
      </view>
      <view class="right-actions">
        <button 
          class="action-button add-cart"
          :disabled="!selectedSku"
          @tap="addToCart"
        >加入购物车</button>
        <button 
          class="action-button buy-now"
          :disabled="!selectedSku"
          @tap="buyNow"
        >立即购买</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getProductVoByIdUserUsingGet } from '@/backend/productController';
import { getProductReviewVoByIdUsingPost } from '@/backend/productReviewController';
import { addCartUsingPost } from '@/backend/cartController';
import { tokenStore } from '@/store/tokenStore';
import type { API } from '../../backend/typings';
import { delayNavigateBack } from "@/utils/navigate";
import ProductReviews from '@/components/product-reviews/index.vue';

const product = ref<API.ProductVO>();
const selectedSku = ref<API.ProductSKUVO>();
const buyQuantity = ref(1);
const store = tokenStore();
const currentSwiperIndex = ref(0);
const isNameExpanded = ref(false);
const isDescExpanded = ref(false);

// 计算所有图片列表
const allImages = computed(() => {
  const images = [];
  if (product.value?.image) {
    images.push(product.value.image);
  }
  if (product.value?.productSKUVOList) {
    product.value.productSKUVOList.forEach(sku => {
      if (sku.image) {
        images.push(sku.image);
      }
    });
  }
  return images;
});

// 处理轮播图切换
const handleSwiperChange = (e: any) => {
  const current = e.detail.current;
  currentSwiperIndex.value = current;
  
  // 如果不是第一张图（主图），则选中对应的SKU
  if (current > 0 && product.value?.productSKUVOList) {
    const targetSku = product.value.productSKUVOList[current - 1];
    if (targetSku?.stock && targetSku.stock > 0) {
      selectSku(targetSku, current);
    }
  }
};

// 预览图片
const previewImage = (url?: string) => {
  if (!url) return;
  uni.previewImage({
    urls: allImages.value,
    current: url
  });
};

// 选择规格
const selectSku = (sku: API.ProductSKUVO, index?: number) => {
  selectedSku.value = sku;
  buyQuantity.value = 1; // 重置购买数量
  // 更新轮播图索引
  if (typeof index === 'number') {
    currentSwiperIndex.value = index;
  }
};

// 更新购买数量
const updateBuyQuantity = (delta: number) => {
  const newQuantity = buyQuantity.value + delta;
  if (selectedSku.value && newQuantity >= 1 && newQuantity <= selectedSku.value.stock) {
    buyQuantity.value = newQuantity;
  }
};

// 加入购物车
const addToCart = async () => {
  if (!selectedSku.value) {
    uni.showToast({
      title: '请选择商品规格',
      icon: 'none'
    });
    return;
  }

  try {
    const res = await addCartUsingPost({
      skuId: selectedSku.value?.id,
      quantity: buyQuantity.value
    });

    if (res.code === 0) {
      uni.showToast({
        title: '加入购物车成功',
        icon: 'success'
      });
      delayNavigateBack()
    } else {
      uni.showToast({
        title: res.message || '加入购物车失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('加入购物车失败：', error);
    uni.showToast({
      title: '加入购物车失败',
      icon: 'none'
    });
  }
};

// 立即购买
const buyNow = () => {
  if (!selectedSku.value) {
    uni.showToast({
      title: '请选择商品规格',
      icon: 'none'
    });
    return;
  }

  // 准备订单信息
  const orderInfo = {
    productSKU: selectedSku.value,
    quantity: buyQuantity.value
  };

  // 跳转到订单确认页面
  uni.navigateTo({
    url: `/pages/order/confirm?info=${encodeURIComponent(JSON.stringify(orderInfo))}`
  });
};

// 跳转到购物车
const goToCart = () => {
  uni.switchTab({
    url: '/pages/cart/cart'
  });
};

// 评论相关
const reviews = ref<API.ProductReviewVO[]>([]);
const total = ref(0);
const hasMore = ref(true);
const currentPage = ref(1);
const pageSize = ref(5);
const loading = ref(false);
const productId = ref<number>();

// 获取商品评论
const fetchReviews = async (refresh = false) => {
  if (!productId.value || loading.value || (!hasMore.value && !refresh)) return;

  if (refresh) {
    currentPage.value = 1;
    reviews.value = [];
    hasMore.value = true;
  }

  loading.value = true;
  try {
    const res = await getProductReviewVoByIdUsingPost({
      productId: productId.value,
      current: currentPage.value,
      pageSize: pageSize.value,
      sortField: 'createTime',
      sortOrder: 'desc'
    });

    if (res.code === 0 && res.data) {
      const newReviews = res.data;
      reviews.value = refresh ? newReviews : [...reviews.value, ...newReviews];
      total.value = newReviews.length;
      hasMore.value = newReviews.length >= pageSize.value;
      
      if (hasMore.value) {
        currentPage.value++;
      }
    }
  } catch (error) {
    console.error('获取商品评论失败：', error);
    uni.showToast({
      title: '获取评论失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 加载更多评论
const loadMoreReviews = () => {
  if (!loading.value && hasMore.value) {
    fetchReviews();
  }
};

// 页面加载时获取商品ID并请求详情
onLoad((options) => {
  const id = Number(options?.id);
  if (id && !isNaN(id)) {
    productId.value = id; // 保存商品ID
    fetchProductDetail(id);
    fetchReviews(true); // 获取评论
  } else {
    uni.showToast({
      title: '商品ID无效',
      icon: 'none'
    });
  }
});

// 自动选择最低价格商品
const selectLowestPriceSku = () => {
  if (!product.value?.productSKUVOList?.length) return;
  
  const availableSkus = product.value.productSKUVOList.filter(sku => sku.stock && sku.stock > 0);
  if (!availableSkus.length) return;

  const lowestPriceSku = availableSkus.reduce((prev, current) => {
    return (prev.price || 0) <= (current.price || 0) ? prev : current;
  });

  selectSku(lowestPriceSku);
};

// 获取商品详情
const fetchProductDetail = async (id: number) => {
  try {
    const token = store.getToken;
    const options = token ? {
      header: {
        'Authorization': token
      }
    } : undefined;

    const res = await getProductVoByIdUserUsingGet(
      { id: id },
      options
    );

    if (res?.code === 0 && res?.data) {
      product.value = res.data;
      // 自动选择最低价格商品
      selectLowestPriceSku();
    }
  } catch (error) {
    console.error('获取商品详情失败：', error);
    uni.showToast({
      title: '获取商品详情失败',
      icon: 'none'
    });
  }
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 100rpx;
}

.product-swiper {
  width: 100%;
  height: 750rpx;
}

.product-image {
  width: 100%;
  height: 100%;
}

.product-info {
  background: #fff;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.price-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx 40rpx;
  align-items: baseline;
}

.price {
  font-size: 52rpx;
  color: #e4393c;
  font-weight: 700;
  text-shadow: 0 2rpx 4rpx rgba(228, 57, 60, 0.1);
}

.original-price {
  font-size: 28rpx;
  color: #999;
  text-decoration: line-through;
  margin-right: 20rpx;
}

.stock-info {
  background: #fef2f2;
  color: #e4393c;
  padding: 8rpx 24rpx;
  border-radius: 40rpx;
  font-size: 26rpx;
}

.sales-info {
  font-size: 24rpx;
  color: #666;
  background: #fff2ed;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.name-section, .desc-section {
  position: relative;
  margin-bottom: 12rpx;
}

.name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  transition: all 0.3s ease;
}

.name.expanded {
  -webkit-line-clamp: unset;
}

.desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  transition: all 0.3s ease;
}

.desc.expanded {
  -webkit-line-clamp: unset;
}

.expand-btn {
  position: absolute;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, rgba(255,255,255,0) 0%, #fff 20%);
  padding-left: 80rpx;
}

.selected-desc {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.selected-info {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 2rpx solid #f5f5f5;
}

.label {
  font-size: 28rpx;
  color: #666;
  margin-right: 24rpx;
}

.value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.selected-desc {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  margin-right: 32rpx;
}

.quantity-control {
  display: flex;
  align-items: center;
  background: #f8f8f8;
  border-radius: 36rpx;
  padding: 4rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  border: 2rpx solid #eee;
}

.quantity-btn {
  width: 56rpx;
  height: 56rpx;
  padding: 0;
  margin: 0;
  line-height: 56rpx;
  text-align: center;
  background: #fff;
  border-radius: 28rpx;
  color: #333;
  font-weight: 500;
  font-size: 32rpx;
  position: relative;
  transition: all 0.2s ease;
}

.quantity-btn::after {
  content: '';
  border: none;
}

.quantity-btn:active {
  transform: scale(0.95);
  background: #f2f2f2;
}

.quantity-btn.disabled {
  background: #f5f5f5;
  color: #ccc;
  transform: none;
}

.quantity {
  width: 80rpx;
  text-align: center;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.specs-section {
  background: #fff;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  position: relative;
  padding-left: 24rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 24rpx;
  background: #ff5722;
  border-radius: 3rpx;
}

.specs-scroll {
  width: 100%;
  white-space: nowrap;
}

.specs-row {
  display: inline-flex;
  padding: 10rpx 0;
}

.spec-item {
  position: relative;
  border: 2rpx solid #f5f5f5;
  border-radius: 16rpx;
  padding: 16rpx;
  background: #fff;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  width: 300rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
  cursor: pointer;
}

.spec-item.active {
  border-color: #ff5722;
  transform: translateY(-4rpx);
  box-shadow: 0 8rpx 24rpx rgba(255, 87, 34, 0.15);
}

.spec-item.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.spec-item:not(.disabled):active {
  transform: scale(0.96);
}

.spec-image {
  width: 100%;
  height: 200rpx;
  border-radius: 12rpx;
  background: #f5f5f5;
  margin-bottom: 16rpx;
}

.spec-info {
  width: 100%;
}

.spec-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  margin-bottom: 12rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.spec-price-info {
  display: flex;
  align-items: baseline;
  margin-bottom: 8rpx;
}

.spec-price {
  font-size: 32rpx;
  color: #ff5722;
  font-weight: 600;
  margin-right: 12rpx;
}

.spec-original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.spec-stock {
  font-size: 24rpx;
  color: #666;
  padding: 4rpx 12rpx;
  background: #f8f8f8;
  border-radius: 4rpx;
  display: inline-block;
}

.spec-stock.low-stock {
  color: #ff5722;
  background: #fff2ed;
}

.selected-mark {
  position: absolute;
  right: -2rpx;
  top: -2rpx;
  width: 48rpx;
  height: 48rpx;
  background: #ff5722;
  border-radius: 0 16rpx 0 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mark-icon {
  color: #fff;
  font-size: 24rpx;
  transform: scale(0.8);
}

.detail-section {
  background: #fff;
  padding: 24rpx;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.left-actions {
  display: flex;
  margin-right: 24rpx;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 24rpx;
}

.action-icon {
  width: 40rpx;
  height: 40rpx;
  margin-bottom: 4rpx;
}

.action-item text {
  font-size: 20rpx;
  color: #666;
}

.right-actions {
  flex: 1;
  display: flex;
  gap: 20rpx;
}

.action-button {
  flex: 1;
  height: 72rpx;
  border-radius: 36rpx;
  font-size: 28rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
}

.action-button:active {
  transform: scale(0.96);
}

.action-button::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 200%;
  height: 200%;
  background: rgba(255,255,255,0.2);
  transform: translate(-50%, -50%) scale(0);
  border-radius: 50%;
  transition: all 0.4s ease;
}

.action-button:active::after {
  transform: translate(-50%, -50%) scale(1);
  opacity: 0;
}

.add-cart {
  background: #fff2ed;
  color: #ff5722;
  border: 2rpx solid #ff5722;
}

.buy-now {
  background: #ff5722;
  color: #fff;
}

.action-button:disabled {
  opacity: 0.6;
}

/* 统一其他区域的标题样式 */
.specs-section .section-title,
.detail-section .section-title {
  padding-left: 24rpx;
}

.specs-section .section-title::before,
.detail-section .section-title::before {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 24rpx;
  border-radius: 3rpx;
}

/* 图片轮播指示点美化 */
.product-swiper ::v-deep .wx-swiper-dot {
  width: 10rpx;
  height: 10rpx;
  background: rgba(255,255,255,0.6);
  transition: all 0.3s ease;
}

.product-swiper ::v-deep .wx-swiper-dot-active {
  width: 30rpx;
  background: #fff;
  border-radius: 6rpx;
}

/* 输入框聚焦状态 */
.quantity-input:focus {
  background: rgba(255,87,34,0.05);
  border-radius: 8rpx;
}
</style> 